package com.guli.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.guli.common.to.esmodel.SkuEsModel;
import com.guli.common.constant.EsConstant;
import com.guli.search.service.IndexService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class IndexServiceImpl implements IndexService {
    @Autowired
    private RestHighLevelClient esClient;

    @Override
    public boolean productUp(List<SkuEsModel> skuEsModels) {
        //将skuEsModels上传到es
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.forEach(skuEsModel -> {
            log.info(JSON.toJSONString(skuEsModel));
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX)
                    .id(skuEsModel.getSkuId().toString())
                    .source(JSON.toJSONString(skuEsModel),XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        try {
            BulkResponse responses = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            boolean hasFailures = responses.hasFailures();
            return !hasFailures;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
